package com.chenailin.www.service;

import com.chenailin.www.common.Schedule;
import com.chenailin.www.dao.DepartmentDAO;
import com.chenailin.www.dao.DoctorDAO;
import com.chenailin.www.daoimpl.DepartmentDAOImpl;
import com.chenailin.www.daoimpl.DoctorDAOImpl;
import com.chenailin.www.exception.ServiceException;
import com.chenailin.www.pojo.Doctor;

import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

public class DoctorService {
    // 面向接口编程
    private final DoctorDAO doctorDAO = new DoctorDAOImpl();
    private final DepartmentDAO departmentDAO = new DepartmentDAOImpl();

    // 添加医生
    public boolean addDoctor(Doctor doctor) {
        // 1. 数据验证
        validateDoctor(doctor);
        // 2. 数据库操作
        try {
            boolean isDoctorAdded = doctorDAO.addDoctor(doctor);
            boolean isScheduleAdded = doctorDAO.addSchedule(doctor.getDocId(), doctor.getSchedule());
            return isDoctorAdded && isScheduleAdded;
        } catch (SQLException e) { // 明确捕获SQL异常
            throw new ServiceException("添加医生失败", e);
        }
    }

    // 删除医生
    public boolean deleteDoctor(int doctorId) {
        try {
            return doctorDAO.deleteDoctor(doctorId) && doctorDAO.deleteAllSchedule(doctorId);
        } catch (SQLException e) {
            throw new ServiceException("删除医生失败", e);
        }
    }

//    public boolean deleteDoctor(int doctorId) throws Exception{
//        Connection conn = null;
//        try {
//            conn = DBUtil.getConnection(); // 从工具类获取连接
//            conn.setAutoCommit(false);    // 开启事务
//            // 1. 先删除关联的排班记录
//            int scheduleDeleted = doctorDAO.deleteScheduleByDoctorId(conn, doctorId);
//            // 2. 再删除医生主记录
//            int doctorDeleted = doctorDAO.deleteDoctorById(conn, doctorId);
//            if (doctorDeleted == 0) {
//                conn.rollback(); // 回滚事务
//                return false;
//            }
//            conn.commit(); // 提交事务
//            return true;
//        } catch (SQLException e) {
//            if (conn != null) {
//                try {
//                    conn.rollback(); // 异常回滚
//                } catch (SQLException ex) {
//                    ex.printStackTrace();
//                }
//            }
//            System.err.println("删除医生失败: " + e.getMessage());
//            return false;
//        } finally {
//            DBUtil.release(conn); // 归还连接
//        }
//    }

    // 修改医生
    public boolean modifyDoctor(Doctor doctor) {
        validateDoctor(doctor);
        try {
            return doctorDAO.modifyDoctor(doctor)
                    && doctorDAO.deleteAllSchedule(doctor.getDocId())
                    && doctorDAO.addSchedule(doctor.getDocId(), doctor.getSchedule());
        } catch (SQLException e) {
            throw new ServiceException("修改医生信息失败", e);
        }
    }

    // 查看所有医生
    public List<Doctor> getAllDoctors() {
        return doctorDAO.getAllDoctors();
    }

    // 查看医生详情
    public Doctor getDoctorDetail(int id) {
        return doctorDAO.findById(id);
    }

    // 查询医生有空的时间段
    public List<Integer> getUnSelectedSchedule(int docId) {
        return doctorDAO.getUnSelectedSchedule(docId);
    }

    // 添加时间段
    public boolean addSchedule(int doctorId, List<Integer> schedule) {
        try {
            return doctorDAO.addSchedule(doctorId, schedule);
        } catch (SQLException e) { // 明确捕获SQL异常
            throw new ServiceException("添加时间段失败", e);
        }
    }

    // 删除时间段
    public boolean deleteSchedule(int doctorId, List<Integer> schedule) {
        try {
            return doctorDAO.deleteSchedule(doctorId, schedule);
        } catch (SQLException e) { // 明确捕获SQL异常
            throw new ServiceException("删除时间段失败", e);
        }
    }

    // 查找对应部门的所有医生
    public List<Doctor> findDoctorByDepartment(int departId)  {
        try {
            // 验证数据库中是否有此账号
            List<Doctor> doctors = doctorDAO.findDoctorByDepartment(departId);
            if(doctors==null) {
                System.out.println("此部门暂无医生！");
                return null;
            }
            return doctors;
        } catch (SQLException e) { // 明确捕获SQL异常
            throw new ServiceException("查找对应部门的所有医生失败", e);
        }
    }

    // 是否为有效医生
    private void validateDoctor(Doctor doctor) throws IllegalArgumentException {
        // id是否重复
        if (doctorDAO.findById(doctor.getDocId()) != null) {
            throw new IllegalArgumentException("医生id重复");
        }

        // 姓名非空检查
        if(doctor.getDocName() == null || doctor.getDocName().trim().isEmpty()) {
            throw new IllegalArgumentException("医生姓名不能为空");
        }

        // 科室存在性检查
         if(departmentDAO.findById(doctor.getDepartmentId()) == null) {
             throw new IllegalArgumentException("科室不存在");
         }

        // 时间段有效性检查
        List<Integer> validSchedule = Schedule.getValidSlots();
        for(Integer slot : doctor.getSchedule()) {
            if(!validSchedule.contains(slot)) {
                throw new IllegalArgumentException("无效时间段编号：" + slot);
            }
        }
    }

    // 过滤重复排班 ???
    public List<Integer> filterSchedule(int doctorId, List<Integer> toAdd) {
        if (toAdd == null || toAdd.isEmpty()) return Collections.emptyList();

        Doctor doctor = doctorDAO.findById(doctorId);
        if (doctor == null) throw new IllegalArgumentException("医生不存在");

        Set<Integer> existing = new HashSet<>(doctor.getSchedule());
        return toAdd.stream()
                .filter(slot -> !existing.contains(slot))
                .distinct()
                .collect(Collectors.toList());
    }
}
